<template>
    <div id="home">
        <!-- 导航栏 -->
        <NavButtons />

        <!-- 背景模糊切换层 -->
        <div class="background-wrapper">
            <img :src="currentBackground" class="background background-current" />
            <img :src="nextBackground" class="background background-next" />
        </div>

        <!-- 时间轴区域 -->
        <div class="shell">
            <div class="header">
                <h2 class="title">复古游戏博物馆</h2>
                <h3 class="subtitle">HOME_HISTORY</h3>
            </div>

            <div class="timeline">
                <div v-for="(event, idx) in events" :key="idx" class="item"
                    :class="{ even: idx % 2 === 1, 'item--active': idx === activeIndex }" :data-text="event.title">
                    <div class="content">
                        <img class="img" :src="getSmallImage(event)" alt="timeline image" />
                        <h2 class="content-title">{{ event.year }}</h2>
                        <p class="content-desc">{{ event.desc }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 页脚 -->
        <div class="footer">
            <a>复古游戏博物馆</a>
        </div>

        <!-- 返回顶部按钮 -->
        <BackToTop />
    </div>
</template>

<script>
import NavButtons from '@/components/NavButtons.vue'
import events from '@/assets/data/gameHistory.json'
import { onMounted, ref } from 'vue'
import BackToTop from '@/components/BackToTop.vue'

const images = import.meta.glob('../assets/img_home/*.jpg', { eager: true })

export default {
    name: 'Home',
    components: {
        NavButtons,
        BackToTop
    },
    setup() {
        const activeIndex = ref(0)
        const currentBackground = ref('')
        const nextBackground = ref('')
        const backgroundLayer = ref(0)

        const findImageByYear = (year) => {
            const yearStr = String(year)
            for (const path in images) {
                if (path.includes(`/${yearStr}`)) {
                    return images[path].default
                }
            }
            return ''
        }

        const getSmallImage = (event) => {
            return findImageByYear(event.year)
        }

        const getBackgroundImage = (event) => {
            return findImageByYear(event.year)
        }

        const switchBackground = (url) => {
            if (backgroundLayer.value === 0) {
                nextBackground.value = url
                backgroundLayer.value = 1
            } else {
                currentBackground.value = url
                backgroundLayer.value = 0
            }
        }

        const preloadAndSwitch = (url) => {
            const img = new Image()
            img.src = url
            img.onload = () => {
                switchBackground(url)
            }
        }

        const onScroll = () => {
            const items = document.querySelectorAll('.item')
            const scrollPos = window.scrollY
            const windowCenter = scrollPos + window.innerHeight / 2 - 100 // 计算视口中线位置

            // 处理顶部边界情况
            if (scrollPos < 100) {
                activeIndex.value = 0
                preloadAndSwitch(getBackgroundImage(events[0]))
                return
            }

            // 遍历时间轴项，检测哪个项位于视口中部
            items.forEach((item, idx) => {
                const itemTop = item.offsetTop
                const itemBottom = itemTop + item.clientHeight

                // 处理倒数第二项的特殊情况（避免最后一个项无法触发）
                if (idx === items.length - 2 && windowCenter > itemTop + item.clientHeight / 2) {
                    activeIndex.value = items.length - 1
                    preloadAndSwitch(getBackgroundImage(events[events.length - 1]))
                }
                // 普通项：如果视口中线位于当前项范围内，则激活该项
                else if (windowCenter >= itemTop && windowCenter <= itemBottom) {
                    activeIndex.value = idx
                    preloadAndSwitch(getBackgroundImage(events[idx]))
                }
            })
        }

        onMounted(() => {
            const firstBg = getBackgroundImage(events[0])
            currentBackground.value = firstBg
            preloadAndSwitch(firstBg)
            window.addEventListener('scroll', onScroll)
        })

        return { events, activeIndex, getSmallImage, currentBackground, nextBackground }
    }
}
</script>

<style scoped>
/* 背景模糊层 */
.background-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
}

@keyframes breathe {
    0% {
        transform: scale(1);
    }

    50% {
        transform: scale(1.05);
    }

    100% {
        transform: scale(1);
    }
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    filter: blur(10px) brightness(0.7);
    transition: opacity 1s ease-in-out;
    opacity: 0;
    animation: breathe 20s ease-in-out infinite;
    /* 加上呼吸动效 */
}

.background-current {
    z-index: 1;
    opacity: 1;
}

.background-next {
    z-index: 2;
}

/* 其他 CSS（完全保持你的原版布局） */
.shell {
    width: 100%;
    position: relative;
    padding: 80px 0;
}

.header {
    width: 100%;
    text-align: center;
    margin-bottom: 80px;
    position: relative;
}

.title {
    color: #fff;
    font-size: 46px;
    font-weight: normal;
    margin: 0;
}

.subtitle {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
    letter-spacing: 5px;
    margin-top: 10px;
    font-weight: normal;
}

.timeline {
    display: flex;
    margin: 0 auto;
    flex-wrap: wrap;
    flex-direction: column;
    max-width: 700px;
    position: relative;
}

.timeline:before {
    position: absolute;
    left: 50%;
    width: 2px;
    height: 100%;
    margin-left: -1px;
    background: rgba(255, 255, 255, 0.07);
    content: "";
}

.item {
    padding: 40px 0;
    opacity: 0.3;
    filter: blur(2px);
    transition: 0.5s;
    box-sizing: border-box;
    width: calc(60% - 40px);
    display: flex;
    position: relative;
    transform: translateY(-80px);
    flex-direction: column;
    align-items: center;
}

.item.even {
    align-self: flex-end;
}

.item:before {
    content: attr(data-text);
    letter-spacing: 3px;
    width: 100%;
    position: absolute;
    color: rgba(255, 255, 255, 0.5);
    border-left: 2px solid rgba(255, 255, 255, 0.5);
    top: 70%;
    margin-top: -5px;
    padding-left: 15px;
    opacity: 0;
    right: calc(-100% - 56px);
    font-weight: 900;
    font-size: 30px;
    letter-spacing: 5px;
}

.item.even:before {
    right: auto;
    text-align: right;
    left: calc(-100% - 56px);
    padding-left: 0;
    border-left: none;
    border-right: 2px solid rgba(255, 255, 255, 0.5);
    padding-right: 15px;
}

.item--active {
    opacity: 1;
    transform: translateY(0);
    filter: blur(0px);
}

.item--active:before {
    top: 50%;
    transition: 0.3s all 0.2s;
    opacity: 1;
}

.content {
    text-align: center;
}

.img {
    max-width: 100%;
    box-shadow: 0 10px 15px rgba(0, 0, 0, 0.4);
}

.content-title {
    font-weight: normal;
    font-size: 66px;
    margin: -10px 0 0 0;
    transition: 0.4s;
    padding: 0 10px;
    box-sizing: border-box;
    color: #fff;
}

.content-desc {
    margin: 0;
    font-size: 20px;
    box-sizing: border-box;
    color: rgba(255, 255, 255, 0.7);
    line-height: 25px;
}

.footer {
    padding: 95px 0;
    text-align: center;
}

.footer a {
    color: #999;
    display: inline-block;
}

@media only screen and (max-width: 767px) {
    .item {
        align-self: baseline !important;
        width: 100%;
        padding: 0 30px 150px 80px;
    }

    .item:before {
        left: 10px !important;
        padding: 0 !important;
        top: 50px;
        text-align: center !important;
        width: 60px;
        border: none !important;
    }

    .item:last-child {
        padding-bottom: 40px;
    }

    .timeline:before {
        left: 40px;
    }
}
</style>